'use strict';

const Controller = require('egg').Controller;

class BuildingController extends Controller {
  // 新增楼栋
  async insertManyBuildings() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    const payload = ctx.request.body;
    const buildings = payload.buildings;
    const res = await ctx.service.building.insertManyBuildings(buildings);
    if (res.errcode) {
      resMsg.errcode = 1;
      resMsg.errorBuildings = res.errorBuildings;
      resMsg.msg = "操作失败，请查看！";
    }
    ctx.body = resMsg;
  }

  // /**
  //  * @desc 更新楼栋信息
  //  * @apiParam 楼栋信息,
  //  */
  // async updateBuilding() {
  //   const { ctx } = this;
  //   let resMsg = { errcode: 0, data: {}, msg: 'success' };

  //   const building = await ctx.service.building.findBuildingByNumber(ctx.request.body.building_num);
  //   if (building && building._id.toString() !== ctx.request.body.id) {
  //     resMsg = {
  //       errcode: 1,
  //       data: {},
  //       msg: '更新失败，楼栋号重复！',
  //     };
  //     ctx.body = resMsg;
  //     return false;
  //   }

  //   const res = await ctx.service.building.updateBuildingById(ctx.request.body.id);

  //   if (!res) {
  //     resMsg = {
  //       errcode: 1,
  //       data: {},
  //       msg: '该楼栋不存在',
  //     };
  //   }
  //   ctx.body = resMsg;

  // }

  /**
   * @desc 根据楼栋号查找楼栋
   * @apiParam building_num
   */
  async findBuildingByNum() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    const building_num = ctx.query.building_num * 1;

    if (!building_num) {
      resMsg.errcode = 1;
      resMsg.msg = "请输入楼栋号！";
      ctx.body = resMsg;
      return false;
    }

    ctx.service.building.findBuildingByNumber(building_num);
    ctx.body = resMsg;
  }

  // 查找所有楼栋
  async findAllBuilding() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    resMsg.data = await ctx.service.building.findAllBuilding();
    ctx.body = resMsg;
  }

  // 查询楼栋
  async searchBuildings() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    const conditions = ctx.request.body;
    resMsg.data = await ctx.service.building.searchBuildings(conditions);
    ctx.body = resMsg;
  }
  // 删除一个楼栋
  async removeOneBuilding() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    const id = ctx.request.body.id;
    const res = await ctx.service.building.removeOneBuilding(id);
    if (res.errcode) {
      resMsg.errcode = res.errcode;
      resMsg.errors = res.errors;
      resMsg.msg = "删除失败";
    }
    ctx.body = resMsg;
  }

  // 修改楼栋信息
  async updateBuilding() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    const payload = ctx.request.body;
    const res = await ctx.service.building.updateBuilding(payload);
    if (res.errcode) {
      resMsg.errcode = res.errcode;
      resMsg.msg = res.msg;
    }
    ctx.body = resMsg;
  }
}

module.exports = BuildingController;
